package com.goldsign.pay.common.util;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by xiaojingjing on 2018/5/10.
 */
public class QueryBeanUtil {

    public static <T> T buildVoFromRequest(HttpServletRequest request, Class<T> clazz) {
        T vo = null;
        try {
            vo = clazz.newInstance();

//            Field[] fields = clazz.getDeclaredFields();
            Field[] fields = getAllField(clazz);
            for (Field field : fields) {
                Object value = request.getParameter(field.getName());
                field.setAccessible(true);
                if (value != null&&!"".equals(value)) {
                    if (field.getType().equals(Long.class)) {
                        field.set(vo, Long.valueOf(value.toString()));
                    } else if (field.getType().equals(Integer.class)) {
                        field.set(vo, Integer.valueOf(value.toString()));
                    } else if (field.getType().equals(String.class)) {
                        field.set(vo, value);
                    } else if (field.getType().equals(Date.class)) {
                        Date d = new java.util.Date(((java.util.Date) value).getTime());
                        field.set(vo, d);
                    }
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return vo;
    }

    /**
     * 获取类clazz的所有Field，包括其父类的Field，如果重名，以子类Field为准。
     * @param clazz
     * @return Field数组
     */
    public static Field[] getAllField(Class<?> clazz) {
        ArrayList<Field> fieldList = new ArrayList<Field>();
        Field[] dFields = clazz.getDeclaredFields();
        if (null != dFields && dFields.length > 0) {
            fieldList.addAll(Arrays.asList(dFields));
        }

        Class<?> superClass = clazz.getSuperclass();
        if (superClass != Object.class) {
            Field[] superFields = getAllField(superClass);
            if (null != superFields && superFields.length > 0) {
                for(Field field:superFields){
                    if(!isContain(fieldList, field)){
                        fieldList.add(field);
                    }
                }
            }
        }
        Field[] result=new Field[fieldList.size()];
        fieldList.toArray(result);
        return result;
    }

    /**检测Field List中是否已经包含了目标field
     * @param fieldList
     * @param field 带检测field
     * @return
     */
    public static boolean isContain(ArrayList<Field> fieldList,Field field){
        for(Field temp:fieldList){
            if(temp.getName().equals(field.getName())){
                return true;
            }
        }
        return false;
    }
}
